﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;

namespace vlcplay
{
    public class processByte
    {
        /// <summary>
        /// 16进制字符串转换为整数
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private int StringToInt(string str)
        {
            try
            {
                byte[] bts = Encoding.UTF8.GetBytes(str);
                int num = 0;
                foreach (char item in bts)
                {
                    int temp = 0;
                    if (item > 96 && item < 103)//a ~ f
                    {
                        temp = item - 96 + 9;
                    }
                    else if (item > 64 && item < 71)//A ~ F
                    {
                        temp = item - 64 + 9;
                    }
                    else if (item > 47 && item < 58)//0 ~ 9
                    {
                        temp = item - 48;
                    }
                    num = num * 16 + temp;
                }
                return num;
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 带空格字符串转换为报文
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public byte[] StringTOMsg(string str)
        {
            try
            {
                string[] seperators = { " " };
                string[] tempArr = str.Split(seperators, System.StringSplitOptions.RemoveEmptyEntries);
                int len = tempArr.Length;
                byte[] msgData = new byte[len];
                for (int i = 0; i < len; i++)
                {
                    msgData[i] = (byte)StringToInt(tempArr[i]);
                }
                return msgData;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 字节转字符串 中间用空格隔开
        /// </summary>
        /// <returns></returns>
        public string ByteToString(byte[] command)
        {
            StringBuilder commandStr = new StringBuilder();
            foreach (byte item in command)
            {
                commandStr.Append(item.ToString("x2"));
                commandStr.Append(" ");
            }
            return commandStr.ToString();
        }
    }

}
